package com.xbongbong.saas.help;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.LinkInfoPojo;
import com.xbongbong.paas.field.LinkedAttrPoJo;
import com.xbongbong.paas.help.FormDataFormExplainHelper;
import com.xbongbong.paas.pojo.SummaryDataPoJo;
import com.xbongbong.paas.pojo.dto.ParseSingleRowDataDTO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.pro.domain.entity.LabelEntity;
import com.xbongbong.pro.domain.entity.LabelGroupEntity;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.formdata.pojo.dto.FormDataDetailDTO;
import com.xbongbong.pro.formdata.pojo.vo.FormDataVO;
import com.xbongbong.pro.formexplain.pojo.dto.HandlerExplainDTO;
import com.xbongbong.pro.label.pojo.LabelForDetailUpadatePojo;
import com.xbongbong.pro.label.pojo.LabelPojo;
import com.xbongbong.pro.permission.pojo.dto.VerifyUpdatePermissionDTO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.model.LabelGroupModel;
import com.xbongbong.saas.model.LabelModel;
import com.xbongbong.sys.help.ProPermissionHelp;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author guohui.zhang
 * @Title: 标签设置help
 * @date 2021/1/1916:55
 */
@Component
public class LabelHelp {

    private final static Logger LOG = LoggerFactory.getLogger(LabelHelp.class);

    @Resource
    private LabelModel labelModel;

    @Resource
    private LabelGroupModel labelGroupModel;

    @Resource
    private FormDataFormExplainHelper formDataFormExplainHelper;


    /**
     * 初始化标签
     *
     * @param corpid
     * @param appId
     * @param formId
     * @param businessType
     * @param userId
     * @param flag         true 需要去对businessType 进行校验
     *                     false 无脑初始化
     * @throws XbbException
     */
    public void initLabel(String corpid, Long appId, Long formId, Integer businessType, String userId, Boolean flag) throws XbbException {
        if (flag) {
            List<Integer> businessTypes = Arrays.asList(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), XbbRefTypeEnum.CLUE.getCode(), XbbRefTypeEnum.MARKET_ACTIVITY.getCode());
            if (!businessTypes.contains(businessType)) {
                return;
            }
        }
        // 判断是否有过标签标签分组
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid", corpid);
        param.put("formId", formId);
        param.put("appId", appId);
        // 这儿就不添加del条件了
        Integer count = labelGroupModel.getEntitysCount(param);
        try {
            if (count <= 0) {
                LabelGroupEntity labelGroupEntity = new LabelGroupEntity();
                labelGroupEntity.setId(null);
                labelGroupEntity.setCorpid(corpid);
                labelGroupEntity.setAppId(appId);
                labelGroupEntity.setFormId(formId);
                labelGroupEntity.setBusinessType(businessType);
                labelGroupEntity.setGroupName(I18nMessageUtil.getMessage(PaasConstant.DEFAULT_LABEL_GROUP));
                labelGroupEntity.setSort(BasicConstant.ONE);
                labelGroupEntity.setCreatorId(userId);
                labelGroupModel.save(labelGroupEntity);
                LabelEntity labelEntity = new LabelEntity();
                labelEntity.setCorpid(corpid);
                labelEntity.setAppId(appId);
                labelEntity.setFormId(formId);
                labelEntity.setBusinessType(businessType);
                labelEntity.setName(I18nMessageUtil.getMessage(PaasConstant.DEFAULT_LABEL_NAME));
                labelEntity.setColor(I18nMessageUtil.getMessage(PaasConstant.DEFAULT_LABEL_COLOR));
                labelEntity.setSort(BasicConstant.ZERO);
                labelEntity.setEnable(BasicConstant.ZERO);
                labelEntity.setCreatorId(userId);
                labelEntity.setGroupId(labelGroupEntity.getId());
                labelModel.insert(labelEntity);
            }
        } catch (XbbException e) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    /**
     * 初始化以及删除全部的标签
     *
     * @param formEntities
     * @param targetCorpid
     * @param appId
     */
    public void deleteAllAndinit(Collection<PaasFormEntity> formEntities, String targetCorpid, Long appId) {
        List<Integer> businessTypes = Arrays.asList(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), XbbRefTypeEnum.CLUE.getCode(), XbbRefTypeEnum.MARKET_ACTIVITY.getCode());
        List<Long> formIds = new ArrayList<>();
        formEntities.forEach(item -> {
            formIds.add(item.getId());
        });
        // 先把原先的标签标签分组都删除 , 再新增一个默认标签,默认标签分组
        labelGroupModel.deleteByFormIds(formIds, targetCorpid, appId);
        labelModel.deleteByFormIds(formIds, targetCorpid, appId);
        long now = DateUtil.getNow();
        List<LabelGroupEntity> labelGroupEntities = new ArrayList<>();
        formEntities.forEach(item -> {
            if (businessTypes.contains(item.getBusinessType()) && Objects.equals(item.getDel(), DelEnum.NORMAL.getDel())) {
                LabelGroupEntity labelGroupEntity = new LabelGroupEntity();
                labelGroupEntity.setId(null);
                labelGroupEntity.setCorpid(item.getCorpid());
                labelGroupEntity.setAppId(appId);
                labelGroupEntity.setFormId(item.getId());
                labelGroupEntity.setBusinessType(item.getBusinessType());
                labelGroupEntity.setGroupName(I18nMessageUtil.getMessage(PaasConstant.DEFAULT_LABEL_GROUP));
                labelGroupEntity.setSort(BasicConstant.ONE);
                labelGroupEntity.setUpdateTime(now);
                labelGroupEntity.setAddTime(now);
                labelGroupEntity.setDel(DelEnum.NORMAL.getDel());
                labelGroupEntity.setCreatorId(item.getCreatorId());
                labelGroupEntities.add(labelGroupEntity);
            }
        });
        if (labelGroupEntities.size() > 0) {
            labelGroupModel.insertBatch(labelGroupEntities, targetCorpid);
            List<LabelEntity> labelEntities = new ArrayList<>();
            labelGroupEntities.forEach(item -> {
                LabelEntity labelEntity = new LabelEntity();
                labelEntity.setCorpid(item.getCorpid());
                labelEntity.setAppId(appId);
                labelEntity.setFormId(item.getFormId());
                labelEntity.setBusinessType(item.getBusinessType());
                labelEntity.setName(I18nMessageUtil.getMessage(PaasConstant.DEFAULT_LABEL_NAME));
                labelEntity.setColor(I18nMessageUtil.getMessage(PaasConstant.DEFAULT_LABEL_COLOR));
                labelEntity.setSort(BasicConstant.ZERO);
                labelEntity.setEnable(BasicConstant.ZERO);
                labelEntity.setCreatorId(item.getCreatorId());
                labelEntity.setGroupId(item.getId());
                labelEntity.setUpdateTime(now);
                labelEntity.setAddTime(now);
                labelEntity.setDel(DelEnum.NORMAL.getDel());
                labelEntities.add(labelEntity);
            });
            labelModel.insertBatch(labelEntities, targetCorpid);
        }

    }

    /**
     * 单条数据标签id 转化为pojo
     *
     * @param labelAttr
     * @param dataJsonObject
     */
    public void dealId2Pojo4One(String labelAttr, JSONObject dataJsonObject, Map<Long, LabelPojo> labelPojoMap) throws XbbException {
        try {
            if (StringUtil.isNotEmpty(labelAttr)) {
                // 查询对应的标签
                JSONArray jsonArray = dataJsonObject.getJSONArray(labelAttr);
                JSONArray jsonArray1 = new JSONArray();
                if (CollectionsUtil.isNotEmpty(jsonArray)) {
                    jsonArray.forEach(item -> {
                        if(item instanceof  Integer){
                            if (Objects.nonNull(labelPojoMap.get(Long.parseLong(item.toString())))) {
                                jsonArray1.add(labelPojoMap.get(Long.parseLong(item.toString())));
                            }
                        }
                    });
                }
                dataJsonObject.put(labelAttr, jsonArray1);
            }
        } catch (Exception e) {
            LOG.error("标签转化失败", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    /**
     * 处理label标签 转化标签id为标签pojo
     * 移除回收站中的标签
     *
     * @param corpid
     * @param dataList
     * @param labelAttr
     */
    public void removeRecycleLabel(String corpid, JSONObject dataList, String labelAttr) throws XbbException {
        try {
            List<LabelForDetailUpadatePojo> labelPojos = dataList.getJSONArray(labelAttr).toJavaList(LabelForDetailUpadatePojo.class);
            List<Long> labelIds = new ArrayList<>();
            labelPojos.forEach(item -> {
                labelIds.add(item.getId());
            });
            if (labelIds.size() > 0) {
                //查出对应的标签是否有被删除
                List<LabelEntity> byLabelIds = labelModel.getByLabelIds(labelIds, corpid);
                labelIds.clear();
                byLabelIds.forEach(item -> {
                    if (Objects.equals(item.getEnable(), BasicConstant.ZERO)) {
                        labelIds.add(item.getId());
                    }
                });
                if (labelIds.size() != labelPojos.size()) {
                    List<LabelForDetailUpadatePojo> labelPojoReplace = new ArrayList<>();
                    labelPojos.forEach(item -> {
                        if (labelIds.contains(item.getId())) {
                            labelPojoReplace.add(item);
                        }
                    });
                    dataList.put(labelAttr, labelPojoReplace);
                }
            }
        } catch (Exception e) {
            LOG.error("移除回收站的标签失败", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    /**
     * 批量把多条数据标签id转化为实体
     *
     * @param dataList
     * @param parseSingleRowDataDTO
     * @param linkInfoPojo
     * @throws XbbException
     */
    public void changeDataLabel(List<FormDataVO> dataList, ParseSingleRowDataDTO parseSingleRowDataDTO, LinkInfoPojo linkInfoPojo) throws XbbException {
        try {
            List<LinkedAttrPoJo> linkedAttr = linkInfoPojo.getLinkedAttr();
            String lableAttr = null;
            for (LinkedAttrPoJo linkedAttrPoJo : linkedAttr) {
                if (Objects.equals(linkedAttrPoJo.getFieldType(), FieldTypeEnum.LABEL.getType())) {
                    lableAttr = linkedAttrPoJo.getAttr();
                    break;
                }
            }
            Long linkFormId = linkInfoPojo.getLinkFormId();
            String corpid = parseSingleRowDataDTO.getCorpid();
            Long linkAppId = linkInfoPojo.getLinkAppId();
            // 尝试一下把全部标签拿到内存中处理
            dealId2Pojo(dataList, lableAttr, linkFormId, corpid, linkAppId);
        } catch (Exception e) {
            LOG.error("批量转化出错:", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    /**
     * 公共处理(先取出全部标签,然后把id转成pojo)
     *
     * @param dataList
     * @param lableAttr
     * @param linkFormId
     * @param corpid
     * @param linkAppId
     */
    private void dealId2Pojo(List<FormDataVO> dataList, String lableAttr, Long linkFormId, String corpid, Long linkAppId) {
        if (StringUtil.isNotEmpty(lableAttr) && CollectionsUtil.isNotEmpty(dataList)) {
            Map<Long, LabelPojo> labelPojoMap = getLabelMap(linkFormId, corpid, linkAppId);
            for (FormDataVO item : dataList) {
                JSONArray labelIds = item.getData().getJSONArray(lableAttr);
                if (CollectionsUtil.isNotEmpty(labelIds)) {
                    JSONArray labelPojos = new JSONArray();
                    for (Object o : labelIds) {
                        Long lable = Long.parseLong(o.toString());
                        if (Objects.nonNull(labelPojoMap.get(lable))) {
                            labelPojos.add(labelPojoMap.get(lable));
                        }
                    }
                    item.getData().put(lableAttr, labelPojos);
                }

            }
        }
    }

    public Map<Long, LabelPojo> getLabelMap(Long formId, String corpid, Long appId) {
        Map<Long, LabelPojo> labelPojoMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("formId", formId);
        param.put("corpid", corpid);
        param.put("appId", appId);
        param.put("del", DelEnum.NORMAL.getDel());
        List<LabelEntity> entitys = labelModel.findEntitys(param);
        if (CollectionUtils.isEmpty(entitys)) {
            return labelPojoMap;
        }
        entitys.forEach(item -> {
            LabelPojo labelPojo = new LabelPojo();
            labelPojo.setName(item.getName());
            labelPojo.setId(item.getId());
            labelPojo.setColor(item.getColor());
            labelPojoMap.put(item.getId(), labelPojo);
        });
        return labelPojoMap;
    }
    /**
     *处理app端数据标签，包含（1）把数据标签中“标签字段”的移动到最后面(2)判断用户是否有详情页快捷编辑标签的权限，如果有返回标签字段的attr，没有则返回空
     * @param formDataDetailDTO
     * @param labelsList 数据标签
     * @param paasFormDataEntityExt 详情页的数据实体
     * @param explainMap 标签的解释字段
     * @return 标签字段的attr;如果返回空，表示用户没有标签的编辑权限 或者 数据标签那里没有设置"标签"字段
     * @throws XbbException
     */
    public String dealAppDetailLabelListLocation(FormDataDetailDTO formDataDetailDTO, List<SummaryDataPoJo> labelsList,PaasFormDataEntityExt paasFormDataEntityExt, Map<String, FieldAttrEntity> explainMap) throws XbbException {
        FieldAttrEntity labelField = null;
        for (Map.Entry<String, FieldAttrEntity> entry : explainMap.entrySet()) {
            FieldAttrEntity item = entry.getValue();
            if (Objects.equals(FieldTypeEnum.LABEL.getType(), item.getFieldType())) {
                labelField = item;
            }
        }
        if (Objects.isNull(labelField)) {
            return null;
        }
        return dealAppDetailLabelListLocation(formDataDetailDTO, labelsList, paasFormDataEntityExt, labelField);
    }
    /**
     *处理app端数据标签，包含（1）把数据标签中“标签字段”的移动到最后面(2)判断用户是否有详情页快捷编辑标签的权限，如果有返回标签字段的attr，没有则返回空
     * @param formDataDetailDTO
     * @param labelsList 数据标签
     * @param formData 详情页的数据实体
     * @param labelField 标签的解释字段
     * @return 标签字段的attr;如果返回空，表示用户没有标签的编辑权限 或者 数据标签那里没有设置"标签"字段
     * @throws XbbException
     */
    public String dealAppDetailLabelListLocation(FormDataDetailDTO formDataDetailDTO , List<SummaryDataPoJo> labelsList, PaasFormDataEntityExt formData , FieldAttrEntity labelField) throws XbbException {
        //判断数据表单模板的"数据标签"是否含有"标签"
        Boolean haveDataLabel = false;
        if(CollectionsUtil.isNotEmpty(labelsList) && Objects.nonNull(labelField)){
            int labelIndex = -1;
            SummaryDataPoJo labelCopyDataPoJo = new SummaryDataPoJo();
            int size = labelsList.size();
            for(int index = 0;index < size;index++){
                SummaryDataPoJo summaryDataPoJo = labelsList.get(index);
                if (Objects.equals(labelField.getAttr(),summaryDataPoJo.getAttr())) {
                    labelIndex = index;
                    labelCopyDataPoJo = summaryDataPoJo;
                    haveDataLabel = true;
                    break;
                }
            }
            //先移除，再add位置就是最后面(如果index本来就在最后一位，则不需要多余操作)
            if(labelIndex >= 0 && labelIndex != (size-1)){
                labelsList.remove(labelIndex);
                labelsList.add(labelCopyDataPoJo);
            }
        }
        //用户有标签编辑权限 并且 模板的数据标签设置中含有标签
        Boolean haveLabelEditPermission = haveLabelEditPermission(formDataDetailDTO, formData, labelField);
        if(haveLabelEditPermission && haveDataLabel){
            return labelField.getAttr();
        }
        return null;
    }
    /**
     *处理web端数据标签，包含（1）把数据标签中“标签字段”的移动到最后面(2)判断用户是否有详情页快捷编辑标签的权限，如果有返回标签字段的attr，没有则返回空
     * @param formDataDetailDTO
     * @param labelsList 数据标签
     * @param tags web端详情页的tags
     * @param paasFormDataEntityExt 详情页的数据实体
     * @param explainMap 标签的解释字段
     * @return 标签字段的attr;如果返回空，表示用户没有标签的编辑权限 或者 数据标签那里没有设置"标签"字段
     * @throws XbbException
     */
    public String dealWebDetailLabelListLocation(FormDataDetailDTO formDataDetailDTO, JSONArray labelsList, JSONArray tags, PaasFormDataEntityExt paasFormDataEntityExt, Map<String, FieldAttrEntity> explainMap) throws XbbException {
        FieldAttrEntity labelField = null;
        for (Map.Entry<String, FieldAttrEntity> entry : explainMap.entrySet()) {
            FieldAttrEntity item = entry.getValue();
            if (Objects.equals(FieldTypeEnum.LABEL.getType(), item.getFieldType())) {
                labelField = item;
            }
        }
        if (Objects.isNull(labelField)) {
            return null;
        }
        return dealWebDetailLabelListLocation(formDataDetailDTO, labelsList,tags, paasFormDataEntityExt, labelField);
    }
    /**
     *处理web端数据标签，包含（1）把数据标签中“标签字段”的移动到最后面(2)判断用户是否有详情页快捷编辑标签的权限，如果有返回标签字段的attr，没有则返回空
     * @param formDataDetailDTO
     * @param labelsList 数据标签
     * @param tags web端详情页的tags
     * @param formData 详情页的数据实体
     * @param labelField 标签的解释字段
     * @return 标签字段的attr;如果返回空，表示用户没有标签的编辑权限 或者 数据标签那里没有设置"标签"字段
     * @throws XbbException
     */
    public String dealWebDetailLabelListLocation(FormDataDetailDTO formDataDetailDTO, JSONArray labelsList , JSONArray tags , PaasFormDataEntityExt formData , FieldAttrEntity labelField) throws XbbException {
        //判断数据表单模板的"数据标签"是否含有"标签"
        Boolean haveDataLabel = false;
        if(CollectionsUtil.isNotEmpty(labelsList) && Objects.nonNull(labelField)){
            int size = labelsList.size();
            int labelIndex = -1;
            for(int index = 0;index < size;index++){
                JSONObject labelObj = (JSONObject)labelsList.get(index);
                if (Objects.equals(labelField.getAttr(),labelObj.getString("attr"))) {
                    haveDataLabel = true;
                    labelIndex = index;
                    break;
                }
            }
            //web端的标签是在tags里面。如果标签的在"数据标签"的设置里面本来就在最后面，则不需要跳转位置
            if(CollectionsUtil.isNotEmpty(tags) && labelIndex != (size-1)){
                JSONArray labelCopyTags = new JSONArray();
                //倒序删除
                for(int i = tags.size()-1; i >= 0 ; i--){
                    JSONObject tag = (JSONObject) tags.get(i);
                    if(Objects.equals(tag.getString("type"), FieldTypeEnum.LABEL.getAlias())){
                        //删除之前先保存
                        labelCopyTags.add(tag);
                        tags.remove(i);
                    }
                }
                //因为上面是倒序加入labelCopyTags中的，所以这边需要将元素顺序在倒序一下，就是能恢复原来的顺序
                Collections.reverse(labelCopyTags);
                tags.addAll(labelCopyTags);
            }
            //个人标签放在企业标签后面
            if(CollectionsUtil.isNotEmpty(tags)) {
                JSONObject personLabel = null;
                for (int i = 0; i < tags.size(); i++) {
                    JSONObject tag = (JSONObject) tags.get(i);
                    if(Objects.equals(tag.getString("type"), "personLabel")){
                        //删除之前取副本
                        personLabel = tag;
                        tags.remove(i);
                        break;
                    }
                }
                if (Objects.nonNull(personLabel)) {
                    tags.add(personLabel);
                }
            }
        }
        //用户有标签编辑权限 并且 模板的数据标签设置中含有标签
        Boolean haveLabelEditPermission = haveLabelEditPermission(formDataDetailDTO, formData, labelField);
        if(haveLabelEditPermission && haveDataLabel){
            return labelField.getAttr();
        }
        return null;
    }

    /**
     *判断用户有没有该条数据的标签字段的编辑权限
     * @param paasFormDataEntityExt 数据实体
     * @param fieldAttrEntity 表单模板中标签的解释字段
     * @return true 表示有标签的编辑权限;fdlase 表示没有
     * @throws XbbException
     */
    public Boolean haveLabelEditPermission(FormDataDetailDTO formDataDetailDTO, PaasFormDataEntityExt paasFormDataEntityExt, FieldAttrEntity fieldAttrEntity) throws XbbException {
        /*Boolean editPermission = false;
        if (Objects.nonNull(fieldAttrEntity)) {
            String corpid = paasFormDataEntityExt.getCorpid();
            Long formId = paasFormDataEntityExt.getFormId();
            Long dataId = paasFormDataEntityExt.getDataId();
            String creatorId = paasFormDataEntityExt.getCreatorId();
            String ownerId = paasFormDataEntityExt.getOwnerId();

            List<Long> dataIdList = new ArrayList<>(1);
            dataIdList.add(dataId);

            Map<Long, List<String>> mainUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            Map<Long, List<String>> coUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            Boolean hasTeam = UserTeamEnum.hasTeam(businessType);
            if (hasTeam){
                formDataFormExplainHelper.getUserIdMap(dataIdList,corpid,businessType,false,mainUserMap,coUserMap);
            } else {
                CoUserListDTO coUserListDTO = new CoUserListDTO();
                coUserListDTO.setCorpid(corpid);
                coUserListDTO.setFormId(formId);
                coUserListDTO.setFormDataIdIn(dataIdList);
                coUserMap = formDataFormExplainHelper.coUserMap(coUserListDTO);
            }
            Map<Long, List<String>> finalCoUserMap = coUserMap;
            // 负责人，协同人
            List<String> mainUserList = mainUserMap.get(dataId);
            List<String> coUserList = finalCoUserMap.get(dataId);
            HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO();
            handlerExplainDTO.setUserId(userVO.getUserId());
            handlerExplainDTO.setLoginUser(userVO);
            // 获取对应数据
            handlerExplainDTO.setCreatorId(creatorId);
            // 设置创建人
            if (Objects.equals(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), businessType)) {
                handlerExplainDTO.setCreatorId(paasFormDataEntityExt.getData().getString(CustomerManagementEnum.CREATOR.getAttr()));
            } else {
                handlerExplainDTO.setCreatorId(creatorId);
            }
            if (hasTeam) {
                handlerExplainDTO.setOwnerId(mainUserList);
            } else {
                handlerExplainDTO.setOwnerId(Collections.singletonList(ownerId));
            }
            if (coUserList != null && !coUserList.isEmpty()) {
                handlerExplainDTO.setCoUserId(coUserList);
            }
//            Boolean invisible = ExplainUtil.invisibleOfScope(fieldAttrEntity, handlerExplainDTO);
            editPermission = ExplainUtil.isEditableOfScope(fieldAttrEntity, handlerExplainDTO);
        }*/
        if (Objects.isNull(fieldAttrEntity)){
            return false;
        }
        List<String> ownerIdList = (List<String>) paasFormDataEntityExt.getData().get(FieldTypeEnum.OWNERID.getAlias());
        List<String> coUserIdList = (List<String>) paasFormDataEntityExt.getData().get(FieldTypeEnum.COUSERID.getAlias());
        VerifyUpdatePermissionDTO verifyUpdatePermissionDTO = new VerifyUpdatePermissionDTO();
        BeanUtil.copyProperties(formDataDetailDTO, verifyUpdatePermissionDTO);
        HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO(paasFormDataEntityExt.getCreatorId(), ownerIdList,
                coUserIdList, formDataDetailDTO.getUserId(), formDataDetailDTO.getLoginUser());
        return ProPermissionHelp.getEditPermission(verifyUpdatePermissionDTO) && ExplainUtil.isEditableOfScope(fieldAttrEntity, handlerExplainDTO);

    }


    /**
     * 移动端关联数据标签处理,我是没想到移动端那么骚
     * @param jsonArray
     * @param list
     */
    public void getList(JSONArray jsonArray, List<String> list, String corpid, Long formId, Long appId) {
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("formId", formId);
        param.put("corpid", corpid);
        param.put("appId", appId);
        param.put("ids", jsonArray);
        param.put("del", DelEnum.NORMAL.getDel());
        List<LabelEntity> entitys = labelModel.findEntitys(param);
        if (CollectionsUtil.isNotEmpty(entitys)) {
            entitys.forEach(item->list.add(item.getName()));
        }
    }

    /**
     * 获取全部标签信息
     * @param appId
     * @param allFormIds
     * @param code
     */
    public Map getAllLabelList(Long appId, List<Long> allFormIds, int code, String  corpid) {
        Map<Long, LabelPojo> labelPojoMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("formIdIn", allFormIds);
        param.put("corpid", corpid);
        param.put("appId", appId);
        param.put("businessType", code);
        param.put("del", DelEnum.NORMAL.getDel());
        List<LabelEntity> entitys = labelModel.findEntitys(param);
        entitys.forEach(item -> {
            LabelPojo labelPojo = new LabelPojo();
            labelPojo.setName(item.getName());
            labelPojo.setId(item.getId());
            labelPojo.setColor(item.getColor());
            labelPojoMap.put(item.getId(), labelPojo);
        });
        return labelPojoMap;
    }

    public JSONArray getLabelList(Long appId, Long formId, String  corpid) {
        Map<Long, LabelPojo> labelPojoMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<LabelPojo> list = new ArrayList<>();
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("formId", formId);
        param.put("corpid", corpid);
        param.put("appId", appId);
        param.put("del", DelEnum.NORMAL.getDel());
        List<LabelEntity> entitys = labelModel.findEntitys(param);
        JSONArray jsonArray = new JSONArray();
        entitys.forEach(item -> {
            LabelPojo labelPojo = new LabelPojo();
            labelPojo.setName(item.getName());
            labelPojo.setId(item.getId());
            labelPojo.setColor(item.getColor());
            jsonArray.add(labelPojo);
        });
        return jsonArray;
    }
}
